const { create } = require('../../helper/db');
const { now, ok, door } = require('../../helper/util');

/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup 朋友圈
 * @api {POST} api/moment/create 发布朋友圈
 * @apiName api/moment/create
 * @apiExample {js} axios 例子:
 *  axios.post('http://39.105.38.34:8080/api/moment/create', {
 *    moment: '我发的第一条朋友圈哈哈哈',
 *    images: ['http://images.gmonking.com/aaaaaaaa.jpg', 'http://images.gmonking.com/bbbbbbbb.jpg'],
 *    video: 'http://images.gmonking.com/video.mp4',
 *  });
 * @apiParam  {String} moment 朋友圈的文字信息
 * @apiParam  {String[]} [images] 朋友圈的图片
 * @apiParam  {String} [video] 朋友圈的视频
 * @apiSuccess (请求成功) {Object} moment 发布成功的朋友圈
 * @apiuse  ErrorResponse
 */

module.exports = async ctx => {
  var token = ctx.headers.authorization;
  var params = ctx.request.body;
  var user = await door(token);
  var moment = await create('moments', {
    userid: user.id,
    moment: params.moment || '',
    images: JSON.stringify(params.images || []),
    video: params.video || '',
    status: 1, // 朋友圈状态: 1 正常 2 已删除
    createdat: now(),
  })

  // 数据库中取出的 images 是 JSON 串，所以需要解析后给到前端
  moment.images = JSON.parse(moment.images);
  moment.user = user;

  ctx.body = ok(moment);
}
